package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.freemarker.FreemarkerGenerator;
import com.heima.minio.MinIoTemplate;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.search.pojos.SearchArticleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {

    @Autowired
    private FreemarkerGenerator freemarkerGenerator;

    @Autowired
    private MinIoTemplate minIoTemplate;

    @Autowired
    private ApArticleService  apArticleService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Override
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        Map<String,Object> params = new HashMap<>();
        params.put("content", JSONArray.parseArray(content));
        InputStream generate = freemarkerGenerator.generate("article.ftl", params);

        String url = minIoTemplate.uploadFile("", apArticle.getId() + ".html", generate, "html");

        //4.修改ap_article表，保存static_url字段
        apArticle.setStaticUrl(url);
        apArticleService.updateById(apArticle);

        //发送消息，更新数据到ES
        updateMysql2Es(apArticle,content);
    }


    //保存文章后，更新数据到es
    private void updateMysql2Es(ApArticle apArticle, String content){
        SearchArticleVo searchArticleVo = new SearchArticleVo();
        BeanUtils.copyProperties(apArticle,searchArticleVo);
        searchArticleVo.setContent(content);
        kafkaTemplate.send("update.mysql2es",JSON.toJSONString(searchArticleVo));
    }
}
